<?php
/**
 * Created by PhpStorm.
 * User: ruisen
 * Date: 2016/7/22
 * Time: 19:46
 */

namespace Home\Controller;


use Think\Controller;

class CarController extends  HomeController{

    public function index(){
        $plugin['date'] = true;
        $this -> assign("plugin", $plugin);
        $this->display("carInfoList");
    }


    public function addCarInfo(){
               $plugin['date'] = true;
        $this -> assign("plugin", $plugin);
        if(!I("post.")){
            $this -> assign('folder_name',"车辆添加");
            $this -> assign('has_pid', false);
            $this -> display("addCar");
        }else{

            $carModle = M("car");
            $_POST["registerDate"] = time();
            $_POST["chuchangDate"] = date_to_int(trim($_POST["chuchangDate"]));
            $_POST["motDate"] = date_to_int($_POST["motDate"]);
            if($carModle->create()){
                if($carId=$carModle->add()){
                    $stateLog['startdate'] = $_POST["registerDate"];
                    $stateLog['state'] = $_POST['state'];
                    $stateLog['carid'] = $carId;
                    M('CarStateLog')->add($stateLog);
                    $this->success("车辆添加成功",U("showCarInfoList"));
                }
            }
        }

    }

    public function showCarInfoList(){
        $plugin['date'] = true;
        $this -> assign("plugin", $plugin);
        $carModel = M("car");
        $_POST = array_filter($_POST);
        $_POST = array_map(trim,$_POST);
        if(I("post.")){
            if(array_key_exists("keyword",I("post."))){
                $map["carNum"] = array("like","%".I("post.keyword")."%");
            }
            if(array_key_exists("carNum",I("post."))){
                $map["carNum"] = array("like","%".I("post.carNum")."%");
            }
            if(array_key_exists("carType",I("post."))){
                $map["carType"] = array("like","%".I("post.carType")."%");
            }
            if(array_key_exists("color",I("post."))){
                $map["color"] = array("like","%".I("post.color")."%");
            }
            if(array_key_exists("beginTime",I("post."))){
                $map["registerDate"]=array("gt",date_to_int(I("post.beginTime")));
            }
            if(array_key_exists("endTime",I("post."))){
                $map["registerDate"] = array("lt",date_to_int(I("post.endTime")));
            }
            $map = array_filter($map);
            $carList = $carModel->where($map)->order('id desc')->select();
        }else{
            $carList = $carModel->order('id desc')->select();
        }



        foreach($carList as &$car){
            $car['struct'] =  $car['struct']=='0'?'手动':'自动';
         //   $car['state'] = $car['state'] == '0'?'正常':$car['state']=='1'?'维修':"使用";
            if($car['state'] == '0'){
                $car['state'] = '正常';
            }else if($car['state'] == '1'){
                $car['state'] = '维修';
            }else{
                $car['state'] = '使用';
            }
            $car['chuchangdate'] = date("Y-m-d", $car['chuchangdate']);
            if(intval($car['motdate']) < strtotime("+1 month") && intval($car['motdate']) > time()){
                $car["mot"] = true;
                $car["motdistance"] = (intval($car['motdate']) - strtotime(date("Y-m-d")))/3600/24;
            }else{
                $car["mot"] = false;
            }
            $car['motdate'] = date("Y-m-d", $car['motdate']);


        }
        //判断是不是admin角色
        $roleId = M('RoleUser')->where(array('user_id'=>session(C('USER_AUTH_KEY'))))->getField('role_id');
        if($roleId == '1'){
            $auth['admin']= 1;
            $this->assign('auth', $auth);
        }
        $this->assign("carList",$carList);
        $this->display("carInfoList");
    }




    private function showAddPage($menuName,$has_pid = false){
        $this -> assign('folder_name', $menuName);
        $this -> assign('has_pid', $has_pid);
        $this -> display("addInfo");
    }

    public function deleteCarById($id){
        $carModel = M('car');
        if($carModel->where(array('id'=>$id))->delete()){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function deleteInsuranceById($id){
        $insuranceModel = M('CarInsurance');
        if($insuranceModel->where(array('id'=>$id))->delete()){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function editCarById($id){
        $plugin['date'] = true;
        $this -> assign("plugin", $plugin);
        //$this -> assign('controller', $controller);
        $carInfo = M("car")->where(array("id"=>$id))->find();
        if($carInfo){

            $carInfo['chuchangdate'] = date("Y-m-d", $carInfo['chuchangdate']);
            $carInfo['motdate'] = date("Y-m-d", $carInfo['motdate']);


            $this->assign("carInfo",$carInfo);
            $this -> display("editCar");
        }

    }

    public function editInsuranceById($id){
        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $this -> assign("plugin", $plugin);
        $insuranceInfo = M("CarInsurance")->where(array("id"=>$id))->find();
        if($insuranceInfo){

            $insuranceInfo['insurancedate'] = date("Y-m-d", $insuranceInfo['insurancedate']);
            $insuranceInfo['expiredate'] = date("Y-m-d",  $insuranceInfo['expiredate']);


            $this->assign("insuranceInfo",$insuranceInfo);
            $this -> display("editInsurance");
        }

    }


    public function updateCarById(){
        $_POST['motDate'] = date_to_int($_POST['motDate']);
        $_POST['chuchangDate'] = date_to_int($_POST['chuchangDate']);
        $carModel = M('Car');
        $carId = $_POST['id'];
        if(!$carModel->where(array('id'=>$carId,'state'=>$_POST['state']))->find()){

            M("CarStateLog")->where(array('carid'=>$carId,'enddate'=>array('exp','is null')))->setField('enddate',time());
            $carLog['startdate'] = time();
            $carLog['state'] = $_POST['state'];
            $carLog['carid'] = $carId;
            M("CarStateLog")->add($carLog);
        }
        if( M('car')->save(I("post."))){
            $this->success("更新成功");
        }
    }


    public function updateInsuranceById(){
        $_POST['insuranceDate'] = date_to_int($_POST['insuranceDate']);
        $_POST['expireDate'] = date_to_int($_POST['expireDate']);
        $test = M('CarInsurance')->save(I("post."));
        if($test){
            $this->success("更新成功");
        }
    }


    public function getStaff($carId){
        $node = D("Dept");
        $menu = array();
        $menu = $node -> field('id,pid,name') -> where("is_del=0") -> order('sort asc') -> select();
        $tree = list_to_tree($menu);
        $list = tree_to_list($tree);

        $carInfo = M("car")->where(array("id"=>$carId))->field("carnum,motdate")->find();

        $this->assign("carNum",$carInfo["carnum"]);
        $this->assign("motDistance",(intval($carInfo['motdate']) - strtotime(date("Y-m-d")))/3600/24);

        $this->assign('menu', popup_tree_menu($tree));

        $this->display("staff");
    }

    function read($id) {
        if (!empty($id)) {
            $model = M("Dept");
            $dept = tree_to_list(list_to_tree( M("Dept") -> where('is_del=0') -> select(), $id));
            $dept = rotate($dept);
            $dept = implode(",", $dept['id']) . ",$id";

            $where['is_del'] = array('eq', '0');
            $where['dept_id'] = array('in', $dept);
        }

        $keyword = I('keyword');
        if (!empty($keyword)) {
            $where['name'] = array('like', "%$keyword%");
            $where['emp_no'] = array('like', "%$keyword%");
            $where['_logic'] = "OR";
        }

        $model = D("UserView");
        $data = $model -> where($where) -> order('emp_no asc') -> select();
        //echo($model->getLastSql());
        $return['data'] = $data;
        $return['status'] = 1;
        $this -> ajaxReturn($return);
    }


    public function sendNotify(){
        $notifyList = I("post.notifyList");
        $carNotifyModel = M("CarNotify");
        foreach($notifyList as $notify){
            $map['emp_no'] = $notify['emp_no'];
            $map['notify_content'] = $notify['notify_content'];
            $map['notify_emp_no'] = $notify['notify_emp_no'];
            $map['notify_time'] = time();
            $carNotifyModel->add($map);
        }

        $this->success("发送通知成功");
    }

    public function carInsurance(){

        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $this -> assign("plugin", $plugin);
        $inSuranceModle = M("CarInsurance");

        $_POST = array_filter($_POST);
        $_POST = array_map(trim,$_POST);
        if(!I('post.')){
            $insuranceList = $inSuranceModle->order('id desc')->select();

        }else{
            if(array_key_exists("keyword",I("post."))){
                $map["carNum"] = array("like","%".I("post.keyword")."%");
            }
            if(array_key_exists("carNum",I("post."))){
                $map["carNum"] = array("like","%".I("post.carNum")."%");
            }
            if(array_key_exists("type",I("post."))){
                $map["type"] = array("like","%".I("post.type")."%");
            }
            if(array_key_exists("handle",I("post."))){
                $map["handle"] = array("like","%".I("post.handle")."%");
            }
            if(array_key_exists("beginTime",I("post."))){
                $map["expireDate"]=array("gt",date_to_int(I("post.beginTime")));
            }
            if(array_key_exists("endTime",I("post."))){
                $map["expireDate"] = array("lt",date_to_int(I("post.endTime")));
            }
            $map = array_filter($map);
            $insuranceList= $inSuranceModle->where($map)->order('id desc')->select();
        }

        foreach($insuranceList as &$insurance){
            $insurance['insurancedate'] = date("Y-m-d",$insurance['insurancedate']);
            $insurance['expiredate'] = date("Y-m-d", $insurance['expiredate']);
        }
        //判断是不是admin角色
        $roleId = M('RoleUser')->where(array('user_id'=>session(C('USER_AUTH_KEY'))))->getField('role_id');
        if($roleId == '1'){
            $auth['admin']= 1;
            $this->assign('auth', $auth);
        }

        $this->assign("insuranceList",$insuranceList);
        $this->display("insurance");

    }

    public function addInsurance(){

        if(I("post.")){
            $insuranceModel = M("CarInsurance");
            $_POST['insuranceDate'] = date_to_int( $_POST['insuranceDate']);
            $_POST['expireDate'] = date_to_int($_POST['expireDate']);

            if($insuranceModel->create()){
                if($insuranceModel->add()){
                    $this->success("添加车辆保险信息成功");
                }
            }
        }else{
            $plugin['uploader'] = true;
            $plugin['date'] = true;
            $this -> assign("plugin", $plugin);
            $this->display("addInsurance");
        }
    }


    function upload() {
        $this -> _upload();
    }

    function down($attach_id) {
        $this -> _down($attach_id);
    }

    public function  getStateLog($carId){
        $stateLogList = M("CarStateLog")->where(array('carid'=>$carId))->field('state,startdate,enddate,remark')->order("id desc")->select();
        if($stateLogList){
            $state = $stateLogList[0]['state'];
            $this->assign('state',$state);
        }
        foreach($stateLogList as &$stateLog){
            $stateLog['startdate'] = date('Y-m-d',$stateLog['startdate']);
            $stateLog['enddate'] = $stateLog['enddate']?date('Y-m-d',$stateLog['enddate']):"";
          //  $stateLog['state'] = $stateLog['state'] == 0?'正常':$stateLog['state'] == 1?'维修':'使用';
            if($stateLog['state'] == '0'){
                $stateLog['state'] = '正常';
            }else if($stateLog['state'] == '1'){
                $stateLog['state'] = '维修';
            }else{
                $stateLog['state'] = '使用';
            }


        }

        $this->assign("stateList",$stateLogList);
        $this->assign('carId',$carId);
        $this->display('stateLog');
    }

    public function addCarState(){


        $carModel = M('Car');
        $carId = $_POST['carid'];
        if(!$carModel->where(array('id'=>$carId,'state'=>$_POST['state']))->find()){
            $carModel->where(array('id'=>$carId))->setField('state',$_POST['state']);
            M("CarStateLog")->where(array('carid'=>$carId,'enddate'=>array('exp','is null')))->setField('enddate',time());
            $carLog['startdate'] = time();
            $carLog['state'] = $_POST['state'];
            $carLog['carid'] = $carId;
            $carLog['remark'] = $_POST['remark'];
            if( M("CarStateLog")->add($carLog)){
                $this->success('添加成功','U("Car/getStateLog",array("carid"=>$carId))');
            }
        }

    }


}